package com.callbell.cas.authentication.handler;

import java.util.List;
import java.util.Map;

import org.apache.shiro.crypto.hash.Sha512Hash;
import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;

import com.callbell.cas.context.CaptchaContext;
import com.callbell.cas.exception.LoginValidateException;
import com.callbell.cas.util.Encodes;

/**
 * 验证适配器
 * @author xlh
 *
 */
public class AuthenticationHandlerAdapter extends AbstractJdbcUsernamePasswordAuthenticationHandler {
	
	public static final int HASH_INTERATIONS = 264544;

	/** 查询用户信息sql */
	private String queryUserInfoSql;

	@SuppressWarnings({ "deprecation" })
	@Override
	protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) throws AuthenticationException {
		boolean result = false;
		if("1".equals(credentials.getLoginType())){//第三方登录不需要用户名密码认证
			result = true;
		} else {
			String userName = credentials.getUsername();
			String password = credentials.getPassword();
			String querySQL = queryUserInfoSql+" LOWER(u.account) =LOWER(?)";
			List<Map<String,Object>> userList = getJdbcTemplate().queryForList(querySQL, userName);
			Map<String,Object> userMap = null;
			if(userList.size()>0){
				userMap = userList.get(0);
				credentials.setUsername(userMap.get("account").toString());
			}
			if(userMap == null){// 用户不存在
				throw new LoginValidateException(LoginValidateException.NO_USER);
			}
			if("0".equals(userMap.get("status").toString())){// 账户未激活
				throw new LoginValidateException(LoginValidateException.USER_NOT_ACTIVE);
			}
			if("2".equals(userMap.get("status").toString())){ //账户被冻结
				throw new LoginValidateException(LoginValidateException.USER_LOCK);
			}
			
			byte[] salt = Encodes.decodeHex(userMap.get("salt").toString());
			Sha512Hash sha = new Sha512Hash(password, salt, HASH_INTERATIONS);
			String encryptedPassword = sha.toHex();
			if(encryptedPassword.equals(userMap.get("password").toString())){
				//userMap中的密码字段内容。
				result = true;
			}else{
				result = false;
			}
			if (result) {
				CaptchaContext.remove(userName);
			} else {
				Integer attemptLoginCount = CaptchaContext.getAttemptLoginCount(userName);
				if (attemptLoginCount == null) {
					attemptLoginCount = new Integer(0);
				}
				attemptLoginCount++;
				CaptchaContext.setAttemptLoginCount(userName, attemptLoginCount);
			}
		}
		return result;
	}

	public void setQueryUserInfoSql(String queryUserInfoSql) {
		this.queryUserInfoSql = queryUserInfoSql;
	}
}
